package com.zbkj.crmeb.order.channel;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import javax.annotation.Resource;

import com.zbkj.crmeb.chant.model.ChannelMerchant;
import com.zbkj.crmeb.chant.service.IChannelMerchantService;
import com.zbkj.crmeb.enums.ProductTypeEnum;
import com.zbkj.crmeb.enums.StockAreaTempEnum;
import com.zbkj.crmeb.store.model.Supplier;
import com.zbkj.crmeb.store.service.SupplierService;
import net.logstash.logback.encoder.org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.crmeb.core.common.CommonResult;
import com.utils.RestTemplateUtil;
import com.utils.unibuy.client.OpenClient;
import com.utils.unibuy.common.RequestMethod;
import com.utils.unibuy.model.order.OpenApiOrderSaveModel;
import com.utils.unibuy.model.order.OrderSaveGoodsModel;
import com.utils.unibuy.request.order.OrderSaveRequest;
import com.utils.unibuy.response.order.OrderSaveResponse;
import com.utils.unibuy.vo.order.OrderBaseVO;
import com.crmeb.core.config.RestTemplateConfig;
import com.zbkj.crmeb.enums.BarCodeEnum;
import com.zbkj.crmeb.enums.PurchaseOrderChannelTypeEnum;
import com.zbkj.crmeb.order.AbstractStoreOrderService;
import com.zbkj.crmeb.order.StoreOrderFactory;
import com.zbkj.crmeb.store.dao.StoreOrderDao;
import com.zbkj.crmeb.store.model.StoreOrder;
import com.zbkj.crmeb.store.service.StoreProductAttrValueService;
import com.zbkj.crmeb.store.service.StoreProductService;
import com.zbkj.crmeb.store.vo.StoreOrderInfoVo;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class UnibuyStoreOrderServiceImpl extends AbstractStoreOrderService {
    @Autowired
    RestTemplateUtil restTemplateUtil;
    @Resource
    private StoreOrderDao storeOrderDao;
    @Autowired
    RestTemplateConfig restTemplateConfig;
    @Autowired
    StoreProductAttrValueService storeProductAttrValueService;
    @Autowired
    StoreProductService storeProductService;
    @Autowired
    StoreOrderFactory storeOrderFactory;
    @Autowired
    private IChannelMerchantService channelMerchantService;

    @Autowired
    SupplierService supplierService;

    /********* unibuy配置参数  *********/
    @Value("${unibuy.url}")
    private String unibuyUrl;
//    @Value("${unibuy.appId}")
//    private String unibuyAppId;
//    @Value("${unibuy.privateKey}")
//    private String unibuyPrivateKey;
//    @Value("${unibuy.publicKey}")
//    private String unibuyPublicKey;
//    @Value("${unibuy.channelNo}")
//    private String unibuyChannelNo;

    @Override
    public CommonResult<Object> addChannelOrder(StoreOrder storeOrder , List<StoreOrderInfoVo> orderInfoVoList) {
        try {
            orderInfoVoList.forEach(order ->{
                if (9 != storeOrder.getSource()) {
                    storeOrder.setPushOrderNo(order.getChildOrderNumber());
                }

                // 组建订单对象
                OpenApiOrderSaveModel model = new OpenApiOrderSaveModel();
                Supplier supplier = null;
                if(order.getSuppliersId()>0){
                    supplier = supplierService.getById(order.getSuppliersId());

                }else
                {
                    supplier = supplierService.getById(199);
                }

                model.setChannelNo(supplier.getUnibuyChannelno());
                model.setOutNo(storeOrder.getPushOrderNo());
                model.setOrderMessage(storeOrder.getRemark());
                model.setReceiverName(storeOrder.getRealName());
                model.setIdCard(storeOrder.getIdCard());
//                model.setMobPhone(storeOrder.getUserPhone().contains(" ") ? storeOrder.getUserPhone().split(" ")[1] : storeOrder.getUserPhone());
//                model.setProvinceName(storeOrder.getProvince());
//                model.setCityName(storeOrder.getCity());
                setAddress(storeOrder,order.getInfo().getProductInfo().getTempId(),model);
                OrderSaveGoodsModel goodsListModel = new OrderSaveGoodsModel();
                String sourceSkuId = order.getInfo().getProductInfo().getAttrInfo().getSourceSkuId();
//                if(sourceSkuId.startsWith(ProductTypeEnum.UNIBUY.getCode()+"-")){
//                    sourceSkuId = sourceSkuId.replaceFirst(ProductTypeEnum.UNIBUY.getCode()+"-","");
//                }
                if(sourceSkuId.startsWith(supplier.getIsEurope()+"-")){
                    sourceSkuId = sourceSkuId.replaceFirst(supplier.getIsEurope()+"-","");
                }
                goodsListModel.setSkuNo(sourceSkuId);
                goodsListModel.setQuantity(order.getInfo().getCartNum());
                List<OrderSaveGoodsModel> goodsModelList = new ArrayList<>();
                goodsModelList.add(goodsListModel);
                model.setGoodsList(goodsModelList);
                
                pushOrder(storeOrder, model, order,supplier);
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
        return CommonResult.success();
    }

    private void setAddress(StoreOrder storeOrder,Integer tempId,OpenApiOrderSaveModel model){
        //发货地大陆
        if(StockAreaTempEnum.getByTempId(tempId).equals(StockAreaTempEnum.CN)){
            String userPhone = storeOrder.getUserPhone();
            if(userPhone.contains("-")){
                userPhone = userPhone.split("-")[1];
            }else if(userPhone.contains(" ")){
                userPhone = userPhone.split(" ")[1];
            }
            model.setMobPhone(userPhone);
            model.setProvinceName(storeOrder.getProvince());
            model.setCityName(storeOrder.getCity());
            model.setAddress(storeOrder.getUserAddress());
        }else {
            ChannelMerchant merchant = channelMerchantService.getById(storeOrder.getMerId());
            if(!Objects.isNull(merchant)){
                String detail = merchant.getDetail();
                String[] addr = StringUtils.isNotBlank(detail) ? detail.split("\\s+") : new String[1];
                model.setAddress(detail);
                String consigneePhone = merchant.getConsigneePhone();
                if(consigneePhone.contains("-")){
                    consigneePhone = consigneePhone.split("-")[1];
                }else if(consigneePhone.contains(" ")){
                    consigneePhone = consigneePhone.split(" ")[1];
                }
                model.setMobPhone(consigneePhone);
                if(5 == addr.length ){
                    model.setProvinceName(addr[2]);
                    model.setCityName(addr[3]);
                }
            }
        }
    }

    /**
     * 获取buyer商品数据和详情
     * @Description:
     * @author daigb
     * @param @param id 商品barCode
     * @param @return
     * @param @throws Exception
     * @return BuyerProductResDTO
     * @throws
     */
    private void pushOrder(StoreOrder storeOrder, OpenApiOrderSaveModel model, StoreOrderInfoVo orderInfo,Supplier supplier) {
    	String orderId = storeOrder.getSource() == 9 ? storeOrder.getOrderId().split("-")[0] : storeOrder.getOrderId();

        // 创建请求对象
        OrderSaveRequest request = new OrderSaveRequest();
        request.setBizModel(model);
        request.setRequestMethod(RequestMethod.POST);

        // 发送请求
//        OpenClient client = new OpenClient(unibuyUrl, unibuyAppId, unibuyPrivateKey, unibuyPublicKey);
        OpenClient client = new OpenClient(unibuyUrl, supplier.getUnibuyAppid(), supplier.getUnibuyPrivatekey(), supplier.getUnibuyPublickey());
        final OrderSaveResponse response = client.execute(request);
        
    	log.info("--------------- unibuy订单推送结果{} ---------------", JSON.toJSONString(response));
        if (response.isSuccess()) {
        	final OrderBaseVO content = response.getContent();
        	if (content != null) {
                //新增采购单
//                storeOrderFactory.insertPurchaseOrder(storeOrder, true, PurchaseOrderChannelTypeEnum.UNIBUY.getCode());
                storeOrderFactory.insertPurchaseOrder(storeOrder, true,  supplier.getIsEurope());
                //新增采购商品
                storeOrderFactory.insertPurchaseGoods(orderInfo, storeOrder, true, "unibuy成功", content.getOrderNo());
        		StoreOrder storeOrderUpdate = new StoreOrder();
        		storeOrderUpdate.setId(storeOrder.getId());
        		storeOrderUpdate.setPushStatus(1);
        		storeOrderUpdate.setPushMessage("unibuy成功");
                storeOrderDao.updateById(storeOrderUpdate);
                log.info("--------------- unibuy订单推送成功 ---------------");
            }
        } else {
            // 新增采购单
//        	storeOrderFactory.insertPurchaseOrder(storeOrder, false, PurchaseOrderChannelTypeEnum.UNIBUY.getCode());
            storeOrderFactory.insertPurchaseOrder(storeOrder, false,  supplier.getIsEurope());
            // 新增采购商品
        	storeOrderFactory.insertPurchaseGoods(orderInfo, storeOrder, false, JSON.parseObject(JSON.toJSONString(response)).getString("msg"), null);
    		StoreOrder storeOrderUpdate = new StoreOrder();
    		storeOrderUpdate.setId(storeOrder.getId());
    		storeOrderUpdate.setPushStatus(2);
    		storeOrderUpdate.setPushMessage(JSON.parseObject(JSON.toJSONString(response)).getString("msg"));
            storeOrderDao.updateById(storeOrderUpdate);
        
        	log.info("--------------- unibuy订单推送失败{} ---------------", JSON.toJSONString(response));
        }

    }

    @Override
    public CommonResult<Object> cancelChannelOrder(StoreOrder storeOrder, List<StoreOrderInfoVo> orderInfoVoList) {
        return null;
    }

    @Override
    public CommonResult<Object> getOrderInfo(String channelOrderSn) {
        return null;
    }

}
